//
//  CarcircleMainViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/19.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "CarcircleMainViewController.h"
#import "CarcircleCell.h"
#import "UserRes.h"
#import "CarcircleTitleCell.h"
#import "CarcircleDetailViewController.h"
#import "CarcircleCommendCell.h"
@interface CarcircleMainViewController ()
@property (nonatomic, strong) NSMutableArray *topicAry;
@property (nonatomic, strong) NSMutableArray *hotAry;
@end

@implementation CarcircleMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self fetchDataFromNet];
    self.mainTableView.mj_header = [Custom_Mjfresh mj_customMjfreshHeaderSetting:^{
        [self fetchDataFromNet];
    }];
    // Do any additional setup after loading the view.
}


- (void)fetchDataFromNet
{
    // 获取车友圈话题列表
    
//    UserRes *user = [CommonMethod getUser];
//    NSDictionary *params = @{
//                             @"FKEY":[CommonMethod createMD5Key:@"type"],
//                             @"type":self.type,
//                             @"DZTOKEN":user.TOKEN
//
//                             };
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[CommonMethod createMD5Key:@"type"] forKey:@"FKEY"];
    [params setObject:self.type forKey:@"type"];
    UserRes *user = [CommonMethod getUser];
    if (user) {
        [params setObject:user.TOKEN forKey:@"DZTOKEN"];
    }
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_30 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        [self.mainTableView.mj_header endRefreshing];
        [self.topicAry removeAllObjects];
        NSDictionary *resultDict  = response;
        NSArray *ary = [resultDict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0) {
            self.topicAry = [NSMutableArray arrayWithArray:[resultDict objectForKey:@"list"]];
//            [self hideNoDataView];
        } else {
//             [self showNodataView:self.mainTableView.centerY-150 withView:self.mainTableView];
            
        }
//         [self.mainTableView  reloadData];
   
        [self fetchHotDataFromNet];

        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
}


- (void)fetchHotDataFromNet
{
    // 获取车友圈话题列表
    
//    UserRes *user = [CommonMethod getUser];
//    NSDictionary *params = @{
//                             @"FKEY":[CommonMethod createMD5Key:@"NULL"],
//                              @"DZTOKEN":user.TOKEN
//
//
//                             };
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[CommonMethod createMD5Key:@"NULL"] forKey:@"FKEY"];
    UserRes *user = [CommonMethod getUser];
    if (user) {
        [params setObject:user.TOKEN forKey:@"DZTOKEN"];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_CIRCLE_33 params:params md5Paraname:nil success:^(id  _Nullable response) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        [self.mainTableView.mj_header endRefreshing];
        [self.hotAry removeAllObjects];
        NSDictionary *resultDict  = response;
        NSArray *ary = [resultDict objectForKey:@"list"];
        if (ary != nil && ![ary isKindOfClass:[NSNull class]] && ary.count != 0) {
            if (ary.count  > 4) {
                
                 self.hotAry = [NSMutableArray arrayWithArray:[ary subarrayWithRange:NSMakeRange(0, 4)]];
            } else {
                 self.hotAry = [NSMutableArray arrayWithArray:ary];
            }
           
           
        } else {
//            [self showNodataView:self.mainTableView.centerY-150 withView:self.mainTableView];
            
        }
        if (self.hotAry.count+self.topicAry.count == 0) {
              [self showNodataView:self.mainTableView.centerY-150 withView:self.mainTableView];
        } else {
             [self hideNoDataView];
            
        }
        
        [self.mainTableView  reloadData];
        
        
        
        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mainTableView.mj_header endRefreshing];
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
        
    }];
    
    
}





- (void)createUI
{
    
    self.mainTableView.estimatedRowHeight = 200;
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
//    IS_IPHONE_X?44:20
//    self.mainTableView.frame = CGRectMake(0, 0, BOUNDWIDTH, BOUNDHEIGHT-44- (IS_IPHONE_X?94:70));
    [self.mainTableView registerClass:[CarcircleCell class] forCellReuseIdentifier:@"CarcircleCell"];
    [self.mainTableView registerClass:[CarcircleTitleCell class] forCellReuseIdentifier:@"CarcircleTitleCell"];
    [self.mainTableView registerClass:[CarcircleCommendCell class] forCellReuseIdentifier:@"CarcircleCommendCell"];
}



#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.topicAry.count+2;
}
//#pragma mark - 代理方法
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.row == (self.topicAry.count + 1)) {
//        return 200;
//
//    } else {
//        return 0;
//
//    }
//
//}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    switch (section) {
//        case 0:
//        {
//            return 0;
//        }
//            break;
//
//        default:
//        {
//            return 20.0f;
//        }
//            break;
//    }
//    return 0;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDWIDTH, 20.0f)];
//    headView.backgroundColor = Common_Head_Color;
//    NSDictionary *secDict = self.totalCarAry[section-1];
//    UILabel *dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, BOUNDWIDTH-15*2, 20.0f)];
//    dateLabel.text =  [secDict objectForKey:@"title"];
//    dateLabel.font = FONT_SIZE(12);
//    dateLabel.textColor = Common_HeadTitle_Color;
//    [headView addSubview:dateLabel];
//
//    return headView;
//
//}
//

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row< self.topicAry.count) {

    
    
//    CarcircleCell *cell = (CarcircleCell *)[tableView dequeueReusableCellWithIdentifier:@"CarcircleCell" forIndexPath:indexPath];
//
//    [cell setData:self.topicAry[indexPath.row]];
//    return cell;
    
        
        NSString *cellName = [NSString stringWithFormat:@"CarcircleCell%ld%ld",indexPath.section,indexPath.row];
        CarcircleCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if (!cell) {
            cell = [[CarcircleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        }

        [cell setData:self.topicAry[indexPath.row]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

        

    } else if (indexPath.row == self.topicAry.count) {
        CarcircleTitleCell *cell = (CarcircleTitleCell *)[tableView dequeueReusableCellWithIdentifier:@"CarcircleTitleCell" forIndexPath:indexPath];

        [cell setData:@""];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    } else if(indexPath.row == (self.topicAry.count + 1)) {

        CarcircleCommendCell *cell = (CarcircleCommendCell *)[tableView dequeueReusableCellWithIdentifier:@"CarcircleCommendCell" forIndexPath:indexPath];

        [cell setData:self.hotAry];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }else {
        CarcircleTitleCell *cell = (CarcircleTitleCell *)[tableView dequeueReusableCellWithIdentifier:@"CarcircleTitleCell" forIndexPath:indexPath];

        [cell setData:@""];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;

    }
 
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row< self.topicAry.count) {
        NSDictionary *dict = self.topicAry[indexPath.row];
        CarcircleDetailViewController *controller = [[CarcircleDetailViewController alloc] init];
        controller.ID = [dict objectForKey:@"TALK_ID"];
        [self.navigationController pushViewController:controller animated:YES];
    }
 
}

///**每一组的标题*/
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    NSDictionary *secDict = self.totalCarAry[section-1];
//    return [secDict objectForKey:@"title"];
//}
//
///** 右侧索引列表*/
//-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
//{
//    //    [self.set addObject:@"#"];
//    return self.letterAry;
//
//}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
